package com.yj.oa.service;

import com.yj.common.constants.Departments;
import com.yj.common.enums.OAUserLevel;
import com.yj.common.enums.OAUserRoleLevel;
import com.yj.oa.dto.oa.ContractTransferDto;
import com.yj.oa.dto.oa.UpdateStatusDto;
import com.yj.oa.entity.system.*;
import com.yj.oa.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright 2017 (C) Yunjian-VC
 * Created on : 2017/12/4
 * Author     : Unbelievable9
 **/
@Service
public class OAInfoService {

    @Autowired
    private OAUserConfigMapper oaUserConfigMapper;

    @Autowired
    private OADepartmentConfigMapper oaDepartmentConfigMapper;

    @Autowired
    private OAUserInfoMapper oaUserInfoMapper;

    @Autowired
    private OAContractMapper oaContractMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private YMWhitelistMapper ymWhitelistMapper;

    /**
     * 处理OA系统推送的用户信息
     *
     * @param oaUserConfig 用户信息
     */
    public void pushOAUserConfig(OAUserConfig oaUserConfig) {
        oaUserConfigMapper.insertUpdate(oaUserConfig);
    }

    /**
     * 处理OA系统删除用户操作
     * @param userIDList 批量删除用户ID列表
     */
    public void deleteOAUserConfig(List<String> userIDList) {
        oaUserConfigMapper.batchDelete(userIDList);
    }

    /**
     * 处理OA系统推送的组织结构信息
     *
     * @param oaDepartmentConfig 组织结构信息
     */
    public void pushOADepartmentConfig(OADepartmentConfig oaDepartmentConfig) {
        oaDepartmentConfigMapper.insertUpdate(oaDepartmentConfig);
    }

    /**
     * 处理OA系统删除组织结构信息操作
     * @param departmentIDList 批量删除组织结构ID列表
     */
    public void deleteDepartmentConfig(List<Long> departmentIDList) {
        oaDepartmentConfigMapper.batchDelete(departmentIDList);
    }

    /**
     * 根据 main_id 获取合同数量
     *
     * @param main_id
     * @return 合同数量
     */
    public Integer contractCountForMainID(String main_id) {
        return oaContractMapper.getContractCountByMainID(main_id);
    }

    /**
     * 添加合同信息
     *
     * @param oaContract
     */
    public void addContract(OAContract oaContract) {
        oaContractMapper.addContract(oaContract);
    }

    /**
     * 更新合同信息
     *
     * @param oaContract
     */
    public void updateContract(OAContract oaContract) {
        oaContractMapper.updateContract(oaContract);
    }

    /**
     * 更新合同状态
     *
     * @param oaUpdateStatusDto 合同更新请求对象
     */
    public void updateContractStatus(UpdateStatusDto oaUpdateStatusDto) {
        oaContractMapper.updateStatus(oaUpdateStatusDto);
    }

    /**
     * 转让合同
     *
     * @param contractTransferDto 转让合同请求对象
     * @return
     */
    @Transactional
    public Map<String, Object> transferContract(ContractTransferDto contractTransferDto) {
        Map<String, Object> infoMap = null;

        OAUserConfig userConfig = oaUserConfigMapper.getByUserID(contractTransferDto.getSendee_id());

        if (userConfig == null) {
            infoMap = new HashMap<>();
            infoMap.put("status", 0);
            infoMap.put("message", "转让人不存在, 无法装让合同");
        }

        List<OAContract> contractList = oaContractMapper.getByTransferList(contractTransferDto.getTransfer_info());

        if (contractList != null ) {
            for (OAContract oaContract : contractList) {
                oaContractMapper.updateOwnership(oaContract.getMain_id(), userConfig.getUsername(), userConfig.getUser_id());
            }
        } else {
            infoMap = new HashMap<>();
            infoMap.put("status", 0);
            infoMap.put("message", "所有合同均未转让成功");
        }

        /* 取消验证
        if (transferor == null) {
            return "合同转让失败, 转让人并未在可视化系统中绑定过";
        }

        if (sendee == null) {
            return "合同转让失败, 接受人并未在可视化系统中绑定过";
        }

        List<OAContract> contractList = oaContractMapper.getByTransferList(contractTransferDto.getTransfer_info());

        if (contractList != null) {
            for (OAContract oaContract : contractList) {
                if (!oaContract.getUser_id().equals(transferor.getOa_user_id())) {
                    return "转让失败, 业务ID为: " + oaContract.getMain_id() + "不属于该转让人";
                }

                oaContractMapper.updateOwnership(oaContract.getMain_id(), sendee.getOa_username(), sendee.getOa_user_id());
            }
        }
        **/

        return infoMap;
    }

    /**
     * 根据token获取绑定用户信息
     *
     * @param token 用户token
     * @return 绑定用户信息
     */
    public OAUserInfo getOAUserByToken(String token) {
        String oa_user_id = userRelationshipMapper.getOAUserIDByToken(token);

        return oaUserInfoMapper.getOAUserInfoByUserId(oa_user_id);
    }

    public Map<String, Object> getBindingInfo(@NotNull OAUserInfo oaUserInfo) {
        Map<String, Object> infoMap = new HashMap<>();

        infoMap.put("user", oaUserInfo);
        infoMap.put("token", userRelationshipMapper.getTokenByUserID(oaUserInfo.getUser_id()));
        infoMap.put("sub", getSubItemMapByUser(oaUserInfo));

        return infoMap;
    }

    /**
     * 根据用户ID获取用户角色
     *
     * @param oaUserInfo 用户信息
     * @return 错误信息
     */
    public String updateRoleInfoForUser(OAUserInfo oaUserInfo) {

        OAUserConfig oaUserConfig = oaUserConfigMapper.getByUserID(oaUserInfo.getUser_id());

        if (oaUserConfig == null) {
            return "OA用户信息不存在";
        }

        OADepartmentConfig oaDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(oaUserConfig.getDepartment_id());

        if (oaDepartmentConfig == null) {
            return "OA部门信息不存在";
        }

        if (oaDepartmentConfig.getSuperior_department_id().equals(Departments.CCS_DEPARTMENT_ID) &&
                oaDepartmentConfig.getDepartment_name().equals("董事办")) {
            OADepartmentConfig superior = oaDepartmentConfigMapper.getByDepartmentID(oaDepartmentConfig.getSuperior_department_id());

            oaUserInfo.setRole_level(OAUserRoleLevel.CORP);
            oaUserInfo.setCorp(superior.getDepartment_name());
            oaUserInfo.setBu(oaDepartmentConfig.getDepartment_name());
        } else {
            OAUserRoleLevel roleLevel = OAUserRoleLevel.BU;

            OADepartmentConfig currentDepartmentConfig = oaDepartmentConfig;

            Boolean isUnderFirm = false;

            while (!currentDepartmentConfig.getSuperior_department_id().equals(Departments.CCS_DEPARTMENT_ID)) {
                currentDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(currentDepartmentConfig.getSuperior_department_id());

                roleLevel = OAUserRoleLevel.fromValue(roleLevel.value - 1);

                // 级别在分公司以下的特殊处理
                if (roleLevel.equals(OAUserRoleLevel.UNKNOWN)) {
                    roleLevel = OAUserRoleLevel.FIRM;

                    isUnderFirm = true;
                }
            }

            if (oaDepartmentConfig.getDepartment_name().equals("总经办")) {
                roleLevel = OAUserRoleLevel.fromValue(roleLevel.value + 1);
            }

            oaUserInfo.setRole_level(roleLevel);
            currentDepartmentConfig = oaDepartmentConfig;

            if (isUnderFirm) {
                currentDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(oaDepartmentConfig.getSuperior_department_id());
            }

            while (roleLevel.value <= 4) {

                String name = currentDepartmentConfig.getDepartment_name();

                if (name.equals("总经办") || name.equals("董事办")) {
                    roleLevel = OAUserRoleLevel.fromValue(roleLevel.value - 1);
                }

                switch (roleLevel) {
                    case FIRM:
                        oaUserInfo.setFirm(name);
                        break;
                    case BD:
                        oaUserInfo.setBd(name);
                        break;
                    case BU:
                        oaUserInfo.setBu(name);
                        break;
                    case CORP:
                        oaUserInfo.setCorp(name);
                        break;
                }

                currentDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(currentDepartmentConfig.getSuperior_department_id());
                roleLevel = OAUserRoleLevel.fromValue(roleLevel.value + 1);
            }
        }

        // 运营人员
        UserRelationship userRelationship = userRelationshipMapper.getByOAUserID(oaUserInfo.getUser_id());

        if (userRelationship != null && !StringUtils.isEmpty(userRelationship.getYm_user_phone())) {
            YMWhitelist ymWhitelist = ymWhitelistMapper.getByPhone(userRelationship.getYm_user_phone());

            if (ymWhitelist != null && ymWhitelist.getIs_operator()) {
                oaUserInfo.setRole_level(OAUserRoleLevel.OPERATOR);
            }
        }

        return null;
    }

    /**
     * 获取用户部门ID
     * @param user_id 用户ID
     * @return 部门ID
     */
    public Long findDepartmentIDByUserID(String user_id) {
        OAUserConfig oaUserConfig = oaUserConfigMapper.getByUserID(user_id);

        return oaUserConfig.getDepartment_id();
    }

    /**
     * 递归寻找某部门下所有用户（不包括总经办、董事办用户）
     * @param department_id  部门ID
     * @param userIDList 所有用户ID列表
     *
     */
    public void findAllUserForDepartment(Long department_id,
                                          @NotNull List<String> userIDList) {
        List<OADepartmentConfig> oaDepartmentConfigList = oaDepartmentConfigMapper.getSubDepartment(department_id);

        if (oaDepartmentConfigList.size() == 0) {
            List<OAUserConfig> oaUserConfigList = oaUserConfigMapper.subUserForDepartment(department_id);

            if (oaUserConfigList != null) {
                for (OAUserConfig userConfig : oaUserConfigList) {
                    userIDList.add(userConfig.getUser_id());
                }
            }
        } else {
            for (OADepartmentConfig oaDepartmentConfig : oaDepartmentConfigList) {
                if (!(oaDepartmentConfig.getDepartment_name().equals("总经办") ||
                        oaDepartmentConfig.getDepartment_name().equals("董事办"))) {
                    // 过滤总经办和董事办的用户
                    findAllUserForDepartment(oaDepartmentConfig.getDepartment_id(), userIDList);
                }
            }
        }
    }

    /**
     * 获取用户下属信息
     * @param oaUserInfo 用户信息
     * @return 下属信息字典
     */
    public Map<String, Object> getSubItemMapByUser(OAUserInfo oaUserInfo) {
        Map<String, Object> subItemMap = new HashMap<>();

        OAUserConfig oaUserConfig = oaUserConfigMapper.getByUserID(oaUserInfo.getUser_id());

        if (oaUserConfig == null) {
            return null;
        }

        OADepartmentConfig oaDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(oaUserConfig.getDepartment_id());

        if (oaDepartmentConfig == null) {
            return null;
        }

        List<Object> subDepartmentList = null;

        if (oaDepartmentConfig.getDepartment_name().equals("董事办") ||
                oaDepartmentConfig.getDepartment_name().equals("总经办")) {
            subDepartmentList = new ArrayList<>();

            List<OADepartmentConfig> oaDepartmentConfigList =
                    oaDepartmentConfigMapper.subDepartmentForLeader(oaDepartmentConfig.getSuperior_department_id(), oaDepartmentConfig.getDepartment_id());

            for (OADepartmentConfig departmentConfig : oaDepartmentConfigList) {
                Map<String, Object> departmentMap = new HashMap<>();
                departmentMap.put("name", departmentConfig.getDepartment_name());
                departmentMap.put("id", departmentConfig.getDepartment_id());

                subDepartmentList.add(departmentMap);
            }

            subItemMap.put("level", OAUserLevel.AUTHORITY);
        } else {
            if (oaUserConfig.getIs_leader() == 1) {
                subDepartmentList = new ArrayList<>();

                List<OAUserConfig> oaUserConfigList = oaUserConfigMapper.subUserForDepartment(oaUserConfig.getDepartment_id());

                for (OAUserConfig userConfig : oaUserConfigList) {
                    // 如果下属员工没有绑定OA，则隐藏
                    String token = userRelationshipMapper.getTokenByUserID(userConfig.getUser_id());

                    if (token != null) {
                        Map<String, Object> userMap = new HashMap<>();
                        userMap.put("name", userConfig.getUsername());
                        userMap.put("token", userRelationshipMapper.getTokenByUserID(userConfig.getUser_id()));

                        subDepartmentList.add(userMap);
                    }
                }

                subItemMap.put("level", OAUserLevel.LEADER);
            } else {
                subItemMap.put("level", OAUserLevel.SALESMAN);
            }
        }

        subItemMap.put("list", subDepartmentList);

        return subItemMap;
    }
}
